package com.hj.config;

import com.google.code.kaptcha.NoiseProducer;
import com.google.code.kaptcha.util.Configurable;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author < a href="huajian2018@aliyun.com">hj</ a>
 * @Description 图片验证码干扰线
 */
@Component
public class NoNoiseConfig extends Configurable implements NoiseProducer {

    @Override
    public void makeNoise(BufferedImage image, float factorOne,
                          float factorTwo, float factorThree, float factorFour) {

        int width = image.getWidth();
        int height = image.getHeight();
        Random rand = new Random();

        //   使用 float 坐标指定的三次参数曲线段。

        Graphics2D graph = (Graphics2D) image.getGraphics();
        graph.setRenderingHints(new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON));

        // 设置干扰线10条；可以自行设置，每条干扰线的颜色位置都随机产生
        for (int i = 0; i < 10; i++) {
            int xs = rand.nextInt(width);
            int ys = rand.nextInt(height);
            int xe = xs + rand.nextInt(width / 3);
            int ye = ys + rand.nextInt(height / 3);
            graph.setColor(getColor());
            graph.drawLine(xs, ys, xe, ye);
        }

        graph.dispose();
    }

    /**
     * 干扰线 的颜色随机生成
     */
    private Color getColor() {
        Random random = new Random();
        int red = random.nextInt(255);
        int green = random.nextInt(255);
        int blue = random.nextInt(255);
        return new Color(red, green, blue);
    }


}
